import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config } from '../../shared/smartadmin.config';
import { Router,ActivatedRoute} from "@angular/router"; //路由引入
declare var $: any;
@Component({
	selector: 'sa-load-data',
	templateUrl: './load-data.component.html',
	styleUrls: ['./load-data.component.css']
})
export class LoadDataComponent implements OnInit {
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			carNumberInput: {
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择车牌号码'
					}
				}
			},
			spaceTime: {
                validators: {
                    integer: {
                        message: '时间间隔必须是大于等于0的整数'
                    }
                }
            },
            startTime: {
            	trigger:'change',
				validators: {
					notEmpty: {
						message: '请输入起始时间'
					},
					date: {
                        format: 'YYYY-MM-DD h:m:s',
                        message: '请输入正确的时间,例如2018-01-00 00:00:00'
                    }

				}
			},
			endTime:{
				trigger:'change',
				validators: {
					notEmpty: {
						message: '请输入结束时间'
					},
					date: {
                        format: 'YYYY-MM-DD h:m:s',
                        message: '请输入正确的时间,例如2018-01-01 00:00:00'
                    }

				}
			},
			minWeight:{
				validators: {
					callback:{
						callback:function(value,validator,$field){
	                  		if(value){ 
	                  			var reg = /^[+-]{0,1}(\d+)$|^[+-]{0,1}(\d+\.\d{0,2})$/;
	                  			if(!reg.test(value)){
	                  				return{
	                  					valid:false,
		                  				message:'请输入数值(最多两位小数)'
	                  				}
	                  			}else{
	                  				return true;
	                  			}
	                  		}else{
	                  			return true;
	                  		}
	                  	}.bind(this)
					}
				}
			},
			maxWeight:{
				validators: {
					callback:{
						callback:function(value,validator,$field){
	                  		if(value){ 
	                  			var reg = /^[+-]{0,1}(\d+)$|^[+-]{0,1}(\d+\.\d{0,2})$/;
	                  			if(!reg.test(value)){
	                  				return{
	                  					valid:false,
		                  				message:'请输入数值(最多两位小数)'
	                  				}
	                  			}else{
	                  				if(+value > +this.minWeight){
	                  					return true;
	                  				}else{
	                  					return{
		                  					valid:false,
			                  				message:'请输入大于前者的重量'
		                  				}
	                  				}
	                  			}
	                  		}else{
	                  			return true;
	                  		}
	                  	}.bind(this)
					}
				}
			},
			minSpeed:{
				validators: {
					callback:{
						callback:function(value,validator,$field){
	                  		if(value){ 
	                  			var reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d{0,2})$/;
	                  			if(!reg.test(value)){
	                  				return{
	                  					valid:false,
		                  				message:'请输入>=0的正数数值(最多两位小数)'
	                  				}
	                  			}else{
	                  				return true;
	                  			}
	                  		}else{
	                  			return true;
	                  		}
	                  	}.bind(this)
					}
				}
			},
			maxSpeed:{
				validators: {
					callback:{
						callback:function(value,validator,$field){
	                  		if(value){ 
	                  			var reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d{0,2})$/;
	                  			if(!reg.test(value)){
	                  				return{
	                  					valid:false,
		                  				message:'请输入>=0的正数数值(最多两位小数)'
	                  				}
	                  			}else{
	                  				if(+value>+this.minSpeed){
	                  					return true;
	                  				}else{
	                  					return{
		                  					valid:false,
			                  				message:'请输入大于前者的车速'
		                  				}
	                  				}
	                  			}
	                  		}else{
	                  			return true;
	                  		}
	                  	}.bind(this)
					}
				}
			}

		}
	};
	apiType:string='1';//接口类型
	companyId = '';
	carList: any;
	deviceId = ''; //设备ID
	startTime = ''; //开始时间
	endTime = ''; //结束时间
	carNumber = ''; //车牌号码
	selectedCompanyId = '';
	selectedCompanyName = '';
	downloadRate = 0; //下载进度数值
	downloadTimer: any; //进度定时器
	spaceTime: any = 120; //时间间隔
	spaceTime_='';		//下载完成后显示的时间间隔
	speedCalcuStr='';//下载完成后显示的速度范围
	weigthCalcuStr='';//下载完成后显示的重量范围
	isDownFinish = true; //是否下载成功,监听截留下载状态
	downOver = false;
	minSpeed = '';
	maxSpeed = '';
	minWeight = '';
	maxWeight = '';
	isInterface=false;
	lStartTime = 0; //下载时间
	lTimelong = ''; //下载时长
	//基础选项
	fileName = '';
	loadDate = '';
	fileSize = ''; //下载数量总条数
	filePosition = '';
	speedRange = '无';
	weightRange = '无';
	timeSection = '';
	isEqualWeight=false;//速度范围是否选择的等于
	isEqualSpeed=false;//重量范围是否选择的等于
	
	sortParamsArr = [];

	speedCalcu = 'le'; //速度范围的计算方式 
	weigthCalcu = 'le'; //重量范围的计算方式 
	
	defaultSort=[];//默认选项排序
	
	checkArr = [{
			name: '基础选项',
			allChecked: false,
			itemStaus: [{
				keys: "uploadDate",
				value: "时间",
				checked: true
			},{
				keys: "deviceId",
				value: "设备编号",
				checked: true
			},{
				keys: "carNumber",
				value: "车牌号",
				checked: false
			},{
				keys: "weight",
				value: "载重量",
				checked: true
			},{
				keys: "speed",
				value: "车速",
				checked: true
			},{
				keys: "X",
				value: "经度",
				checked: true
			},{
				keys: "Y",
				value: "纬度",
				checked: true
			},{
				keys: "course",
				value: "方位角",
				checked: false
			}]
		},
		{
			name: 'ad信号',
			allChecked: true,
			itemStaus: [{
				keys: "ACH1",
				value: "ACH1",
				checked: true
			},{
				keys: "ACH2",
				value: "ACH2",
				checked: true
			},{
				keys: "ACH3",
				value: "ACH3",
				checked: true
			},{
				keys: "ACH4",
				value: "ACH4",
				checked: true
			},{
				keys: "ACH5",
				value: "ACH5",
				checked: true
			},{
				keys: "ACH6",
				value: "ACH6",
				checked: true
			},{
				keys: "ACH7",
				value: "ACH7",
				checked: true
			},{
				keys: "ACH8",
				value: "ACH8",
				checked: true
			},{
				keys: "ACH9",
				value: "ACH9",
				checked: true
			},{
				keys: "ACH10",
				value: "ACH10",
				checked: true
			},{
				keys: "ACH11",
				value: "ACH11",
				checked: true
			},{
				keys: "ACH12",
				value: "ACH12",
				checked: true
			},{
				keys: "ACH13",
				value: "ACH13",
				checked: true
			},{
				keys: "ACH14",
				value: "ACH14",
				checked: true
			},{
				keys: "ACH15",
				value: "ACH15",
				checked: true
			},{
				keys: "ACH16",
				value: "ACH16",
				checked: true
			}]
		},
		{
			name: '零点信号',
			allChecked: true,
			itemStaus: [{
				keys: "SCH1",
				value: "SCH1",
				checked: true
			},{
				keys: "SCH2",
				value: "SCH2",
				checked: true
			},{
				keys: "SCH3",
				value: "SCH3",
				checked: true
			},{
				keys: "SCH4",
				value: "SCH4",
				checked: true
			},{
				keys: "SCH5",
				value: "SCH5",
				checked: true
			},{
				keys: "SCH6",
				value: "SCH6",
				checked: true
			},{
				keys: "SCH7",
				value: "SCH7",
				checked: true
			},{
				keys: "SCH8",
				value: "SCH8",
				checked: true
			},{
				keys: "SCH9",
				value: "SCH9",
				checked: true
			},{
				keys: "SCH10",
				value: "SCH10",
				checked: true
			},{
				keys: "SCH11",
				value: "SCH11",
				checked: true
			},{
				keys: "SCH12",
				value: "SCH12",
				checked: true
			},{
				keys: "SCH13",
				value: "SCH13",
				checked: true
			},{
				keys: "SCH14",
				value: "SCH14",
				checked: true
			},{
				keys: "SCH15",
				value: "SCH15",
				checked: true
			},{
				keys: "SCH16",
				value: "SCH16",
				checked: true
			}]
		},
		{
			name: '其他选项',
			allChecked: true,
			itemStaus: [{
				keys: "handBrakeHardwareStatus",
				value: "硬件手刹状态",
				checked: true
			},{
				keys: "packageNum",
				value: "流水号",
				checked: true
			},{
				keys: "gpsUploadDate",
				value: "GPS时间",
				checked: true
			},{
				keys: "id",
				value: "id",
				checked: true
			},{
				keys: "createDate",
				value: "上传时间",
				checked: false
			},{
				keys: "rssi",
				value: "信号强度",
				checked: false
			},{
				keys: "lac",
				value: "基站小区区号",
				checked: false
			},{
				keys: "cellid",
				value: "基站小区ID",
				checked: false
			}]
		},
	]
	selected = [];
	jumpData:any;//异常检测-人工页面跳转过来的数据
	
	
	constructor(private jsonApiService: JsonApiService,private activatedRoute: ActivatedRoute ) {
		activatedRoute.queryParams.subscribe(queryParams => {
		
			if(queryParams){
				this.jumpData=queryParams;
			}
		});
	}

	//初始化下载前信息string
	initDownlodStr() {
		this.downloadRate = 0; //下载进度数值
		this.spaceTime_='';
		this.fileName = '';
		this.loadDate = '';
		this.lTimelong = ''; //下载时长
		this.fileSize = '';
		this.filePosition = '';
		this.speedRange = '无';
		this.weightRange = '无';
		this.timeSection = '';

	}
	//选择一组选项事件
	checkedGroupEvent(params) {
		var nowDataArr = this.checkArr[params];
		if(nowDataArr.allChecked) {
			$('#loadForm').data('bootstrapValidator').resetForm();
			for(let i in nowDataArr.itemStaus) {
				if(!nowDataArr.itemStaus[i].checked){
					this.sortParamsArr.push(nowDataArr.itemStaus[i]);
				}
				nowDataArr.itemStaus[i].checked = true;
			}
			this.sortParamsArr = this.uniqueArr(this.sortParamsArr);
		} else {
			for(let i in nowDataArr.itemStaus) {
				nowDataArr.itemStaus[i].checked = false;
				for(let j in this.sortParamsArr){
					if(this.sortParamsArr[j].keys == nowDataArr.itemStaus[i].keys){
						var index=Number(j);
						this.sortParamsArr.splice(index, 1);
					}
				}
			}
		}
	}
	//数组去重复
	uniqueArr(arr) {　　
		var result = [arr[0]];　　
		for(var i = 1; i < arr.length; i++) {　　　　
			var repeat = false;　　　　
			for(var j = 0; j < result.length; j++) {　　　　　　
				if(arr[i] == result[j]) {　　　　　　　　
					repeat = true;　　　　　　　　
					break;　　　　　　
				}　　　　
			}　　　　
			if(!repeat) {　　　　　　
				result.push(arr[i]);　　　　
			}　　
		}　　
		return result;
	}
	//选择单个选项事件 params(i)数据对应index
	checkedItemEvent(i, _i) {
		var isAllChecked = true;
		var nowDataArr = this.checkArr[i].itemStaus;
		var nowIsChecked = nowDataArr[_i].checked; //当前操作的复选框是否选中
		if(nowIsChecked) {
			$('#loadForm').data('bootstrapValidator').resetForm();
			this.sortParamsArr.push(nowDataArr[_i])
		} else {
			for(let j in this.sortParamsArr){
				if(this.sortParamsArr[j].keys==nowDataArr[_i].keys){
					var index=Number(j);
					this.sortParamsArr.splice(index, 1);
				}
			}
		}
		for(let i in nowDataArr) {
			if(!nowDataArr[i].checked) {
				isAllChecked = false;
				break;
			}
		}
		if(isAllChecked) {
			this.checkArr[i].allChecked = true;
		} else {
			this.checkArr[i].allChecked = false;
		}
	}

	//点击手动排序事件,变更下状态并清空所有已选中
	sortParamsEvent() {
		var _len = this.checkArr.length;
		this.sortParamsArr = [];
		for(var i = 0; i < _len; i++) {
			this.checkArr[i].allChecked = false;
			for(var j = 0; j < this.checkArr[i].itemStaus.length; j++) {
				this.checkArr[i].itemStaus[j].checked = false;
			}
		}
	}
	//初始化默认排序
	initCheckSort(){
		var qxdata = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_data-manage:loadDat')));
		var quanXian = false;
		var arr1=[];
		var otherArr=[];
		if(qxdata){
			for(let item of qxdata) {
				if(item.sourceKey === "download:loadAccess" && item.parentId) {
					quanXian = true;
				}
			}	
		}	
		if(quanXian){
			arr1=[
				{keys: "uploadDate",value: "时间",checked: true},
				{keys: "deviceId",value: "设备编号",checked: true},			
				{keys: "weight",value: "载重量",checked: true}
				];
			otherArr=[{
				keys: "handBrakeHardwareStatus",
				value: "硬件手刹状态",
				checked: true
			},{
				keys: "packageNum",
				value: "流水号",
				checked: true
			},{
				keys: "gpsUploadDate",
				value: "GPS时间",
				checked: true
			},{
				keys: "X",
				value: "经度",
				checked: true
			},{
				keys: "Y",
				value: "纬度",
				checked: true
			},{
				keys: "speed",
				value: "车速",
				checked: true
			},{
				keys: "id",
				value: "id",
				checked: true
			}]
			var max=17;
			for(var i=1;i<max;i++){
				var achObj={
					keys: "ACH"+i,
					value: "ACH"+i,
					checked: true
				};
				arr1.push(achObj);
			}
			for(var i=1;i<max;i++){
				var schObj={
					keys: "SCH"+i,
					value: "SCH"+i,
					checked: true
				};
				arr1.push(schObj);
			}
		}
		else{
			arr1=[
				{keys: "uploadDate",value: "时间",checked: true},
				{keys: "deviceId",value: "设备编号",checked: true},		
				{keys: "carNumber",value: "车牌号",checked: true},		
				{keys: "weight",value: "载重量",checked: true},
				
				];
			otherArr=[{
					keys: "speed",
					value: "车速",
					checked: true
				},{
					keys: "X",
					value: "经度",
					checked: true
				},{
					keys: "Y",
					value: "纬度",
					checked: true
				}]
		}
		
		arr1=arr1.concat(otherArr);
		this.sortParamsArr=arr1;
	}
	ngOnInit() {
		this.initCheckSort();
		var qxdata = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_data-manage:loadDat')));
		var quanXian = false;
		for(let item of qxdata) {
			if(item.sourceKey === "download:loadAccess" && item.parentId) {
				quanXian = true;
			}
			
			if(item.sourceKey === "download:interface" && item.parentId) {
				this.isInterface= true;
			}
		}
		if(!quanXian) {
			//当没有权限的更改双项选择框的值
			this.checkArr = [{
				name: '基础选项',
				allChecked: true,
				itemStaus: [{
					keys: "uploadDate",
					value: "时间",
					checked: true
				},{
					keys: "deviceId",
					value: "设备编号",
					checked: true
				},{
					keys: "carNumber",
					value: "车牌号",
					checked: true
				},{
					keys: "weight",
					value: "载重量",
					checked: true
				},{
					keys: "speed",
					value: "车速",
					checked: true
				},{
					keys: "X",
					value: "经度",
					checked: true
				},{
					keys: "Y",
					value: "纬度",
					checked: true
				}]
			}]
		}
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				this.selectCompany(); //初始化select 2 车辆
			});
			System.import('assets/js/jstree/jstree.min.js').then(() => {
				this.initCompanyList();
				var tree_box = document.getElementById('tree_box');
				var company = document.getElementById('company');
				document.onclick = function(e: any) {
					if(!(e.target === company || e.target.className === 'jstree-children' || e.target.className === 's_del_icon' || e.target.className === 'jstree-node  jstree-leaf' || e.target.className === 'jstree-icon jstree-ocl' || e.target.className === 'vision_tree' || e.target.className === 'jstree-node jstree-leaf jstree-closed')) {
						tree_box.className = tree_box.className.replace("tree_open", "");
					}
				}
			})
		});
		this.initDate().then(()=>{
			if(this.jumpData.deviceId){
				this.deviceId=this.jumpData.deviceId;
				this.carNumber=this.jumpData.carNumber;
				this.startTime = this.jumpData.startDate;
				this.endTime = this.jumpData.endDate;
				setTimeout(function(){
					$('#carNumberSelect2').val(this.deviceId).trigger('change');
					var str=$("<span class='select2-selection__rendered'>"+this.carNumber+"</span>");
					$('#carNumberSelect2').val("");
					$("#select2-carNumberSelect2-container").empty();
					$("#select2-carNumberSelect2-container").attr("title","");
					$("#select2-carNumberSelect2-container").prepend(str);
				}.bind(this),100);
			}
		});
	}
	//速度范围方式变更
	speedCalcuChage(){
		if(this.speedCalcu=='eq'){
			this.minSpeed='';
			this.isEqualSpeed=true;
		}else{
			this.isEqualSpeed=false;
		}
	}
	//重量范围方式变更
	weigthCalcuChage(){
		if(this.weigthCalcu=='eq'){
			this.minWeight='';
			this.isEqualWeight=true;
		}else{
			this.isEqualWeight=false;
		}
	}
	//删除所选时间
	del_date(){
		this.startTime = '';
		this.endTime ='';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker2").val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	onSubmit(){	}
	//数据下载
	download() {
		if(!this.isDownFinish) {
			this.jsonApiService.message('数据正在下载中,请勿重复操作....');
			return;
		}
		this.startTime = $('#datetimepicker1').val();
		this.endTime = $('#datetimepicker2').val();
		$('#loadForm').bootstrapValidator('validate'); //开启验证
		let isValid = $('#loadForm').data('bootstrapValidator').isValid();  //验证是否通过
		if(!isValid){
			return
		}
		let timeCheck=common.correctTimeParams(this.startTime,this.endTime,45);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		if(!this.spaceTime){
			this.spaceTime='0';
		}
		this.downOver = false;
		var selectArr = {
			keyArr: [],
			valArr: []
		};
		var _len = this.sortParamsArr.length;
		for(var i = 0; i < _len; i++) {
			selectArr.keyArr.push(this.sortParamsArr[i].keys);
			selectArr.valArr.push(this.sortParamsArr[i].value);
		}
		if(selectArr.keyArr.length < 1) {
			this.jsonApiService.message('请选择需要下载的参数选项');
			return;
		}
		this.initDownlodStr();
		var dataJson = {
			type:this.apiType,
			// minSpeed: this.minSpeed,
			// maxSpeed: this.maxSpeed,
			// minWeight: this.minWeight,
			// maxWeight: this.maxWeight,
			// speedCountType:this.speedCalcu,// 速度范围方式
			// weightCountType:this.weigthCalcu,// 重量范围方式
			deviceId: this.deviceId,
			startTime: this.startTime,
			endTime: this.endTime,
			spaceTime: this.spaceTime,
			title: selectArr.valArr.join(','),
			params: selectArr.keyArr.join(',')
		}
		var reqdata = '';
		for(let item in dataJson) {
			reqdata = reqdata + '&' + item + '=' + dataJson[item];
		}
		this.lStartTime = new Date().getTime();
		this.jsonApiService.http("fileDownload/downloadFile", reqdata).subscribe(result => {
			if(!result.success){
				this.jsonApiService.message(result.message);
				return;
			}
			$('#barWarp').show();
			clearInterval(this.downloadTimer);
			this.isDownFinish = false;
			var that = this;
			var bar = $('#bar');
			this.downloadTimer = setInterval(function() {
				that.readingGetData(bar);
			}, 500)
		})
	}
	readingGetData(bar) {
		this.jsonApiService.http2("fileDownload/getProgress", '').subscribe(result => {
			if(!result.success) {
				clearInterval(this.downloadTimer);
				this.isDownFinish = true;
				$('#bar').animate({width: '0%'}, 1);
				this.jsonApiService.message(result.success);
				return;
			}
			this.downloadRate = parseInt(result.data.progress);
			if(!this.downloadRate){
				this.downloadRate=0;
			}
			//this.downloadRate=this.downloadRate+1;
			bar.width(this.downloadRate + '%');
			//console.log(this.downloadRate,result.data.progress)
			if(this.downloadRate >= 100) {
				clearInterval(this.downloadTimer);
				var pathArr = result.data.filePath.split('/');
				this.fileName = pathArr[pathArr.length - 1];
				this.spaceTime_=this.spaceTime+'秒';
				this.loadDate = getTime(new Date());
				this.fileSize = '共' + result.data.allCount + '条';
				this.filePosition = result.data.filePath;
				this.timeSection = this.startTime + ' ~ ' + this.endTime;
				this.lTimelong = '约' + String((new Date().getTime() - this.lStartTime) / 1000) + '秒';
				this.isDownFinish = true;
				$('#bar').animate({width: '0%'}, 1);
				this.downOver = true;
				$("#loadForm").data('bootstrapValidator').resetForm();
				this.jsonApiService.message('数据下载成功');
				var elemIF = document.createElement("iframe");          
	            elemIF.src = result.data.filePath; 
	            elemIF.style.display = "none";     
	            document.body.appendChild(elemIF);
	            this.getSpeedAndWeightMessage()
			}
		})
	}
	
	//根据选择符号输出重量跟速度的下载结束后的信息提示
	getSpeedAndWeightMessage(){

		if(this.speedCalcu=='le'){
			if(this.minSpeed =='' && this.maxSpeed ==''){ this.speedCalcuStr=''}
			if(this.minSpeed =='' && this.maxSpeed!==''){this.speedCalcuStr='小于等于'+ this.maxSpeed+' km/h'};
			if(this.minSpeed!=='' && this.maxSpeed!==''){this.speedCalcuStr=this.minSpeed+ '小于等于'+ this.maxSpeed+ 'km/h'};
			if(this.minSpeed =='' && this.maxSpeed!==''){this.speedCalcuStr='大于等于'+ this.minSpeed+' km/h'};
			
		}
		else if(this.speedCalcu=='lt'){
			if(this.minSpeed =='' && this.maxSpeed ==''){ this.speedCalcuStr=''}
			if(this.minSpeed =='' && this.maxSpeed!==''){this.speedCalcuStr='小于'+ this.maxSpeed+' km/h'};
			if(this.minSpeed!=='' && this.maxSpeed!==''){this.speedCalcuStr=this.minSpeed+ '小于'+ this.maxSpeed+ 'km/h'};
			if(this.minSpeed =='' && this.maxSpeed!==''){this.speedCalcuStr='大于'+ this.minSpeed+' km/h'};
			
		}
		else if(this.speedCalcu=='eq'){
			if(this.maxSpeed !==''){ this.speedCalcuStr=this.maxSpeed+' km/h'}
			
		}
		
		if(this.weigthCalcu=='le'){
			if(this.minWeight =='' && this.maxWeight ==''){ this.weigthCalcuStr=''}
			if(this.minWeight =='' && this.maxWeight!==''){this.weigthCalcuStr='小于等于'+ this.maxWeight+' 吨'};
			if(this.minWeight!=='' && this.maxWeight!==''){this.weigthCalcuStr=this.minWeight+ '小于等于'+ this.maxWeight+ '吨'};
			if(this.minWeight =='' && this.maxWeight!==''){this.weigthCalcuStr='大于等于'+ this.minWeight+' 吨'};
			
		}
		else if(this.weigthCalcu=='lt'){
			if(this.minWeight =='' && this.maxWeight ==''){ this.weigthCalcuStr=''}
			if(this.minWeight =='' && this.maxWeight!==''){this.weigthCalcuStr='小于'+ this.maxWeight+' 吨'};
			if(this.minWeight!=='' && this.maxWeight!==''){this.weigthCalcuStr=this.minWeight+ '小于'+ this.maxWeight+ '吨'};
			if(this.minWeight =='' && this.maxWeight!==''){this.weigthCalcuStr='大于'+ this.minWeight+' 吨'};
			
		}
		else if(this.weigthCalcu=='eq'){
			if(this.maxWeight !==''){ this.weigthCalcuStr=this.maxWeight+' 吨'}
			
		}
		
	}
	
	getTime(date) {
		var year = date.getFullYear();
		var month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
		var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
		var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
		var minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
		var second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
		return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
	}
	initDate() {
		var that = this;
		return new Promise(function(resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
				() => {
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {

						$("#datetimepicker1").datetimepicker({ //时间插件
							format: "yyyy-mm-dd hh:ii:ss",
							language: "zh-CN",
							autoclose: true,
						}).on("changeDate", function(e) {
							var date = e.date;
							var time = that.getTime(date);
							$("#datetimepicker2").datetimepicker("setStartDate", time);
							$("#datetimepicker1").change();
						});
						$("#datetimepicker2").datetimepicker({ //时间插件
							format: "yyyy-mm-dd hh:ii:ss",
							language: "zh-CN",
							autoclose: true,
						}).on("changeDate", function(e) {
							var date = e.date;
							var time = that.getTime(date);
							$("#datetimepicker1").datetimepicker("setEndDate", time);
							$("#datetimepicker2").change();
						});
						var date = new Date();
						$("#datetimepicker2").val(that.getTime(date)); //当前时间
						date.setDate(date.getDate() - 1); //设置前一周
						$("#datetimepicker1").val(that.getTime(date));
						resolve();
					});
				}
			);
		})
	}
	//擦除公司所选值
	delText() {
		this.selectedCompanyName = '';
		this.selectedCompanyId = '';
		this.deviceId = '';
		this.carNumber = '';
		this.clearSelect2($("#carNumberSelect2")); //清除Select中的数据
		this.selectCompany();
		$('#company').val("");
		this.companySearch();
		if($('#tree_box')[0].className.indexOf('tree_open') > 0) {
			$('#company').focus();
		}
	}
	//打开公司树
	companyClick() {
		$('#tree_box').toggleClass('tree_open');
	}
	//公司树模糊搜索
	companySearch() {
		var value = $('#company').val();
		$("#tree").jstree(true).search(value);
		let searchResult = $('.jstree-search').length;
		if(searchResult < 1) {return};
		$('.jstree-search').each(function(index, obj) {
			if(index < 1) { //js树搜索定位到结果的第一个地方；
				var container = $('#vision_tree'),
					scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({
					scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#vision_tree').height() * 0.3
				});
			}
		})
	}
	
	initCompanyList() {
		var that = this;
		$('#tree').jstree({
			"core": {
				'data': function(obj, callback) {       
					var jsonstr = "[]";       
					var jsonarray = eval('(' + jsonstr + ')');
					var url = 'company/companytree.html';
					$.ajax({        
						type: "GET",
				        url: config.BaseURL + url,
				        dataType: "json",
						xhrFields: {withCredentials: true},
					    success: function(result) {
							jsonarray = result;  
							callback.call(this, jsonarray);
						}         
					});   
				},
				"themes": {
					"responsive": true
				},
				"multiple": false,
				"animation": 200,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"plugins": ["search"]
		}).bind("activate_node.jstree", function(e, obj) {
			var currentNode = obj.node; // 获取当前节点   
			that.selectedCompanyName = currentNode.text;
			that.selectedCompanyId = currentNode.id;
			that.companyId = currentNode.id;
			that.queryCarListByCompanyId(currentNode.id);
			$('#company').val(currentNode.text).change();
			that.companySearch();
		})
	}
	//擦除车牌号码所选值
	del_carNumber() {
		this.deviceId = '';
		this.carNumber = '';
		$("#carNumberInput").val(this.carNumber).change();
		if(this.selectedCompanyId) {
			this.queryCarListByCompanyId(this.selectedCompanyId)
		} else {
			//采用简单粗暴的方法清除;官方推荐的方法失效
			var str = $("<span class='select2-selection__placeholder'>请选择</span>");
			$('#carNumberSelect2').val("");
			$("#select2-carNumberSelect2-container").empty();
			$("#select2-carNumberSelect2-container").attr("title", "");
			$("#select2-carNumberSelect2-container").prepend(str);
		}
	}
	//拉取车辆数据
	selectCompany() {
		var that = this;
		$("#carNumberSelect2").select2({
			language: "zh-CN",
			placeholder: "请选择",
			allowClear: true,
			minimumInputLength: 2, //最少2个字符，select2才显示查询的内容

			ajax: {
				url: config.BaseURL + "stats/carListByCarNumber.html",
				dataType: 'json',
				delay: 50,
				method: "POST",
				xhrFields: {
					withCredentials: true
				},
				data: function(params) {
					return {
						"carNumber": params.term // search term
					};
				},
				processResults: function(data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if(data.data.length<=10){
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if(arr.indexOf(car.carNumber)!=-1){
								sameCar.push(car.carNumber)
							}else{
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function(index, car) {
							if(sameCar.indexOf(car.carNumber)!=-1){
								options.push({
									id: car.deviceId,
									text: car.carNumber+"["+car.parentName+"]"
								})
							}else{
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							}
						});
					}else{
						$(data.data).each(function(index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						});
					}
					return {
						results: options //获取查询后的结果
					};
				},
				cache: true
			},
			templateResult: this.formatRepo
		}).on("select2:select", function(e) {
			var data = e.params.data;
			var data = e.params.data;
			that.deviceId = data.id;
			if(data.text.indexOf('[') > 0){
				that.carNumber = data.text.split('[')[0];
			} else {
				that.carNumber = data.text;
			}
			$("#carNumberInput").val(that.carNumber).change();
		});
	}
	//select2 格式回调函数
	formatRepo(state) {
		if(!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	clearSelect2(obj) {
		obj.empty();
		obj.prepend("<option value=''>请选择</option>");
	}
	//公司id拉取车辆
	queryCarListByCompanyId(companyId) {
		let reqdata = 'companyId=' + companyId;
		this.jsonApiService.http("stats/carlist.html", reqdata).subscribe(data => {
			var carlist = data.data;
			var selectdata = [];
			for(var i = 0; i < carlist.length; i++) {
				var obj = {
					id: carlist[i].deviceId,
					text: carlist[i].carNumber,
				}
				selectdata[i] = obj;
			}
			this.carList = selectdata;
			var selectObj = $("#carNumberSelect2");
			this.clearSelect2(selectObj); //清除Select中的数据
			selectObj.select2({
				language: "zh-CN",
				data: selectdata, //为Select添加数据
				templateResult: this.formatRepo
			});
		})
	}
	showScreenBox(val) {
		val.show();
	}
	hideScreenBox(val) {
		val.hide();
	}
	onChange($event) {
		this.selected = [];
		var len = $event.length;
		for(var i = 0; i < len; i++) {
			if($event[i].selected) {
				this.selected.push($event[i]);
			}
		}
	}
	jumpDownloadSrc(urlSrc) {
		if(urlSrc==''){
			this.jsonApiService.message('文件数据尚未导出,请下载后重试....');
			return;
		}
		window.open(urlSrc);
	}
}